package org.jeecg.modules.simulator.recorder;

import lombok.Getter;
import lombok.Setter;
import org.jeecg.modules.simulator.factory.train.plan.TrainActionRDSFactory;
import org.jeecg.modules.simulator.model.MetroTrain;
import org.jeecg.modules.simulator.model.line.plan.TrainPlanTablePath;
import org.jeecg.modules.simulator.model.orbit.OrbitPath;
import org.jeecg.modules.simulator.model.orbit.OrbitPoint;
import org.jeecg.modules.simulator.model.train.TrainBiz;
import org.jeecg.modules.simulator.model.train.action.TrainActionRecorder;
import org.jeecg.modules.simulator.model.train.action.TrainActionRecorders;
import org.jeecg.modules.simulator.model.train.manager.TrainCalculateBizManager;
import org.jeecg.modules.simulator.util.TimeUtil;
import org.jeecg.modules.simulator.util.UnitCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: simulator-b20240918
 * @description:
 * @author: renzhg
 * @create: 2024-11-29 14:00
 **/
public class TrainManagerPeriodTimeIniter {
    private static final Logger logger = LoggerFactory.getLogger(TrainManagerPeriodTimeIniter.class);
    @Setter
    @Getter
    String lineId;

    TrainCalculateBizManager trainCalculateBizManager = new TrainCalculateBizManager();

    Map<String, OrbitPoint> workUpOrbitPointMap = new HashMap<>();
    Map<String, OrbitPoint> workDownOrbitPointMap = new HashMap<>();
    OrbitPath upOrbitPath;//上行轨道
    OrbitPath downOrbitPath;

    public void init(String lineId, Map<String, OrbitPoint> workUpOrbitPointMap,
                     Map<String, OrbitPoint> workDownOrbitPointMap,
                     OrbitPath upOrbitPath, OrbitPath downOrbitPath) {
        this.lineId = lineId;
        this.workUpOrbitPointMap = workUpOrbitPointMap;
        this.workDownOrbitPointMap = workDownOrbitPointMap;
        this.upOrbitPath = upOrbitPath;
        this.downOrbitPath = downOrbitPath;
    }


    /**
     * @description: 初始化动作记录集合，用来记录所有车的动作记录，
     * 分成两种情况：
     * 1、第一种情况，所有的人都在站点外面等待进入站点，车都存放在场段，所以这里直接在场段初始化车辆。
     * 2、第二种情况，一部分车辆在路网中，一部分车在场段，这个时候需要根据时刻表把车都分成两部分，根据时刻表分别初始化，场段的车辆跟第一种情况一致。在网上的需要根据时刻表初始化车辆位置，
     * 然后，计算车辆的位置，根据车辆的位置，初始化车辆的动作记录表。
     * @author: renzhg
     * @date: 2024/9/14 9:12
     **/
//    public void init(LocalTime startTime, SceneDataType sceneDataType) {
//        try {
//            Map<String, TrainPlanTablePath> trainPlanTablePathMap = trainCalculateBizManager.getTrainPlanTablePathMap();
//            //简单的动态数据加载，所有的车都存在场段
//            if (!sceneDataType.equals(SceneDataType.timePeriodHistoryData)) {
//                allDayTimeParkTrainActionRDsMap(trainPlanTablePathMap);
//            } else {
//                timePeriodAssignTrain(startTime, trainPlanTablePathMap);
//            }
//
//        } catch (Exception e) {
//            logger.debug("初始化车辆动作记录表失败");
//            e.printStackTrace();
//        }
//
//    }






    public Map<String, TrainActionRecorders> timePeriodAssignTrain(LocalTime startTime, Map<String, TrainPlanTablePath> trainPlanTablePathMap) throws Exception {
        Map<String, TrainPlanTablePath> trainPlanTablePathMap1 = trainCalculateBizManager.getTrainPlanTablePathMap();
        Map<String, TrainPlanTablePath> trainPlanTablePathMap2 = trainCalculateBizManager.getTrainPlanTablePathMap();
        for (Map.Entry<String, TrainPlanTablePath> entry : trainPlanTablePathMap.entrySet()) {
            TrainPlanTablePath trainPlanTablePath = entry.getValue();
            //单个站点有问题
            LocalTime firstTime = TimeUtil.convertStringToLocalTime(trainPlanTablePath.getFirstTime());
            LocalTime lastTime = TimeUtil.convertStringToLocalTime(trainPlanTablePath.getLastTime());
            if (firstTime == null || lastTime == null) {
                throw new Exception("初始化车辆动作记录表失败");
            }
            int compareNum1 = TimeUtil.compareLocalTimes(firstTime, startTime);
            int compareNum2 = TimeUtil.compareLocalTimes(lastTime, startTime);
            if (compareNum1 == 1 && compareNum2 == 2) {
                trainPlanTablePathMap1.put(entry.getKey(), trainPlanTablePath);
            } else {
                trainPlanTablePathMap2.put(entry.getKey(), trainPlanTablePath);
            }

        }

        return createTrainActionRecorders(trainPlanTablePathMap1);

    }


    public Map<String, MetroTrain> caculateInNetTimePeriodTrainActionRecorders(
            Map<String, TrainPlanTablePath> trainPlanTablePathMap,
            LocalTime timePoint, String trainType) {
        logger.debug("caculateInNetTimePeriodTrainActionRecorders");

        Map<String, MetroTrain> trainMap = new HashMap<>();
        Map<String, TrainActionRecorders> trainActionRecorders = createTrainActionRecorders(trainPlanTablePathMap);

        trainPlanTablePathMap.forEach((k, v) -> {

            //取出要装配的列车
            MetroTrain metroTrain = new MetroTrain();
            metroTrain.setTrainPhysics(UnitCache.globalSceneBaseData.getTrainPhysicsMap().get(trainType));
            TrainActionRecorders trainActionRecoders = trainActionRecorders.get(k);
            LocalTime fistActionTime = trainActionRecoders.getFistActionTime();
            LocalTime endActionTime = trainActionRecoders.getEndActionTime();
            if (fistActionTime.isBefore(timePoint) && endActionTime.isAfter(timePoint)) {
                metroTrain.setTrainId(trainActionRecoders.getRocordersId().split("-")[0]);
                metroTrain.setTrainNum(trainActionRecoders.getRocordersId().split("-")[1]);
                metroTrain.setBelongLineId(this.lineId);
                //取出第一个动作记录
                if (trainActionRecoders.getFristTrainActionRecorder().getAction().equals("stop")) {


                    String secondName = trainActionRecoders.getSecondTrainActionRecorder().getId();
                    if (judgeUpDictionBySectName(secondName)) {
                        TrainBiz trainBiz = new TrainBiz(workUpOrbitPointMap);
                        metroTrain.setTrainBiz(trainBiz);
                        metroTrain.setIsRuningUp(true);//设立上行方向
                    } else if (judgeDownDictionBySectName(secondName)) {
                        TrainBiz trainBiz = new TrainBiz(workDownOrbitPointMap);
                        metroTrain.setTrainBiz(trainBiz);
                        metroTrain.setIsRuningUp(false);//设立下行方向
                    }

                } else {
                    String sectName = trainActionRecoders.getFristTrainActionRecorder().getId();
                    if (judgeUpDictionBySectName(sectName)) {
                        TrainBiz trainBiz = new TrainBiz(workUpOrbitPointMap);
                        metroTrain.setTrainBiz(trainBiz);
                        metroTrain.setIsRuningUp(true);//设立上行方向
                    } else if (judgeDownDictionBySectName(sectName)) {
                        TrainBiz trainBiz = new TrainBiz(workDownOrbitPointMap);
                        metroTrain.setTrainBiz(trainBiz);
                        metroTrain.setIsRuningUp(false);//设立下行方向
                    }
                }

                boolean isInTimeRange = false;
                while (trainActionRecoders.moveNext()) {
                    TrainActionRecorder currentTrainActionRecorder = trainActionRecoders.getCurrentTrainActionRecorder();
                    int compareStartTime = TimeUtil.compareLocalTimes(currentTrainActionRecorder.getStartTime(), timePoint);
                    int compareEndTime = TimeUtil.compareLocalTimes(currentTrainActionRecorder.getEndTime(), timePoint);
                    if (compareEndTime == 1) {//如果结束时间在当前时间之前，设置动作记录为结束
                        currentTrainActionRecorder.setFinished(true);
                    } else if (compareStartTime == 1 && compareEndTime == 2) {
                        isInTimeRange = true;
                        metroTrain.setOneTimePtInitTrainStatue(currentTrainActionRecorder, timePoint);
                        break;
                    }

                }
                if (metroTrain.getIsRuningUp() != null && isInTimeRange) {
                    trainMap.put(metroTrain.getTrainId() + "-" + metroTrain.getTrainNum(), metroTrain);
                }


            }
        });
        return trainMap;
    }

    /**
     * @description: 初始化场段列车动作记录集合，用来记录所有车的动作记录，
     * @author: renzhg
     * @date: 2024/7/29 9:52
     **/
//    public  Map<String, TrainActionRecorders>   initParkTrainActionRDsMap(Map<String, TrainPlanTablePath> trainPlanTablePathMap) {
//        Map<String, TrainActionRecorders> trainActionRecorders  trainActionRecorders = createTrainActionRecorders(trainPlanTablePathMap);
//        trainActionRdsManager.setTrainActionRecordersMap(trainActionRecorders);
//    }

    /**
     * @description: 时刻表装配动作记录集合
     * @author: renzhg
     * @date: 2024/9/19 9:19
     * @param:
     * @return:
     * @return: java.util.Map<java.lang.String, com.renzhg.gp.gp.simulator.model.train.action.TrainActionRecorders>
     **/
    public Map<String, TrainActionRecorders> createTrainActionRecorders(Map<String, TrainPlanTablePath> trainPlanTablePathMap) {
        return TrainActionRDSFactory.createTrainActionRecorders(trainPlanTablePathMap, this.getLineId());
    }

    private Boolean judgeDownDictionBySectName(String sectName) {

        boolean result = false;

        for (OrbitPoint orbitPoint1 : downOrbitPath) {
            if (orbitPoint1.getOrbitName().equals(sectName)) {
                return true;
            }
        }
        return result;

    }

    private Boolean judgeUpDictionBySectName(String sectName) {

        boolean result = false;
//        if(upOrbitPath.getFirstPointName().equals(firstName))
        for (OrbitPoint orbitPoint1 : upOrbitPath) {
            if (orbitPoint1.getOrbitName().equals(sectName)) {
                return true;
            }
        }
        return result;

    }

}
